/*
 **入职指引 第一步
 */
import React, { useEffect, useImperativeHandle, useState } from 'react';

import { Spin } from 'antd';
import { Accordion, List } from 'antd-mobile';
import { hasIn, size } from 'lodash';
// import { EditListItem } from '@/pages/Recruitment/External/components';
import { createForm } from 'rc-form';
import { useDeepCompareEffect } from 'react-use';

import { defaultFormatResult, useRequest } from '@/hooks';
import { getEntryDevice, getSoft, preloadedSoft } from '@/pages/EntryManage/services';
import { ListItem } from '@/pages/Recruitment/External/components';
import { transformFileList } from '@/pages/Recruitment/utils';

import AvatarUpload from '../AvatarUpload';
import CheckboxPop from '../CheckboxPop';
import MoreSoftware from '../MoreSoftware';
import RadioButton from '../RadioButton';
import styles from './index.less';

const { Item } = List;
// 信息确认
const StepUserInfo = React.forwardRef(({ form, entryPersonnelData }, ref) => {
    const { getFieldProps, setFieldsValue } = form;
    const { idPhoto, dutyName, contractOrganizationName, entryPersonnelCode } = entryPersonnelData;
    const [softTableData, setSoftTableData] = useState([]);
    const [softSelectData, setSoftSelectData] = useState([]);
    const [softWareSelectData, setSoftWareSelectData] = useState([]);
    const [visible, setVisible] = React.useState(false);
    const [visible2, setVisible2] = React.useState(false);
    const [selectedSoft, setSelectedSoft] = React.useState([]);
    const [selectedSoft2, setSelectedSoft2] = React.useState([]);
    useImperativeHandle(ref, () => ({
        form
    }));
    // 电脑偏好
    const deviceTypeList = [
        { name: '笔记本电脑', value: 0 },
        { name: '台式整机', value: 1 }
    ];
    const systemTypeList = [
        { name: 'Windows', value: 0 },
        { name: 'Mac os', value: 1 },
        { name: 'Linux', value: 2 }
    ];
    const hasNeed = [
        { name: '是', value: 1 },
        { name: '否', value: 0 }
    ];

    // 获取通用软件和专业软件数据源
    const { data: softList, loading: softLoading } = useRequest(() => getSoft({ entryPersonnelCode }), {
        refreshDeps: [entryPersonnelCode],
        ready: !!entryPersonnelCode,
        ...defaultFormatResult
    });
    useEffect(() => {
        if (size(softList) > 0) {
            // 将数据源进行分类
            setSoftTableData(softList.filter(item => item.softClass === 0));
            setSoftSelectData(softList.filter(item => item.softClass === 1));
            setSoftWareSelectData(softList.filter(item => item.softClass === 2));
        }
    }, [softList]);
    // 获取已预装软件数据源
    const { data: preloadedSoftData, loading: preloadedSoftLoading } = useRequest(
        () =>
            preloadedSoft({
                entryPersonnelCode,
                choiceType: 0
            }),
        {
            refreshDeps: [entryPersonnelCode],
            ready: !!entryPersonnelCode,
            ...defaultFormatResult
        }
    );
    // 获取已选择设备
    const { data: entryDeviceData } = useRequest(
        () =>
            getEntryDevice({
                entryPersonnelCode,
                choiceType: 0
            }),
        {
            refreshDeps: [entryPersonnelCode],
            ready: !!entryPersonnelCode,
            ...defaultFormatResult
        }
    );

    useDeepCompareEffect(() => {
        const { computerType = 0, needDisplay = 1, needMouse = 1, systemType = 0 } =
            size(entryDeviceData) > 0 ? entryDeviceData[0] : {};
        const { professionalList = [], moreSoftwareList = [] } =
            size(preloadedSoftData) > 0 ? preloadedSoftData[0] : {};
        // 表单回填
        form.setFieldsValue({
            computerType,
            needDisplay,
            needMouse,
            systemType,
            softwareList: professionalList,
            moreSoftwareList,
            idPhoto: transformFileList((size(idPhoto) > 0 && idPhoto[0]?.urlList) || [])
            // idPhoto: transformFileList((size(idPhoto) > 0 && idPhoto[0]?.urlList) || [])
        });
        setSelectedSoft(professionalList);
        setSelectedSoft2(moreSoftwareList);
    }, [entryDeviceData, preloadedSoftData, form, idPhoto, deviceTypeList, systemTypeList, hasNeed]);

    const handleOpenSoftPop = () => {
        setVisible(true);
    };
    const handleOnClose = value => {
        setVisible(value);
    };
    const handleOnChange = value => {
        setFieldsValue({ softwareList: value });
        setSelectedSoft(value);
    };

    const handleOpenSoftWarePop = e => {
        e.stopPropagation();
        setVisible2(true);
    };
    const handleOnCloseSoftWare = value => {
        setVisible2(value);
    };
    const handleOnChangeSoftWare = value => {
        setFieldsValue({ moreSoftwareList: value });
        setSelectedSoft2(value);
    };

    const [accordionActiveKey, setAccordionActiveKey] = useState(['0', '1', '2', '3', '4']);
    return (
        <Spin spinning={softLoading && preloadedSoftLoading}>
            <Accordion
                activeKey={accordionActiveKey}
                accordion={false}
                className={styles.accordionList}
                onChange={setAccordionActiveKey}
            >
                <Accordion.Panel header="入职信息">
                    <List className={styles.softList}>
                        <Item extra={contractOrganizationName}>入职公司</Item>
                        <Item extra={dutyName}>入职岗位</Item>
                    </List>
                </Accordion.Panel>
                <Accordion.Panel header="个人档案">
                    <List className={styles.softList}>
                        <Item
                            multipleLine
                            arrow="horizontal"
                            extra="核对档案"
                            onClick={() => {
                                if (entryPersonnelCode) {
                                    window.open(
                                        `/blank/entryManage/entryEmployeeDetail?entryPersonnelCode=${entryPersonnelCode}`
                                    );
                                    // history.push({
                                    //     pathname: '/blank/entryManage/entryEmployeeDetail',
                                    //     query: { entryPersonnelCode }
                                    // });
                                }
                            }}
                        >
                            档案详情
                        </Item>
                        <ListItem title="证件照" showArrow={false}>
                            <div className={styles.upload}>
                                <AvatarUpload
                                    {...getFieldProps('idPhoto', {
                                        rules: [
                                            {
                                                required: true,
                                                validator(rule, value = [], callback) {
                                                    const result = Array.isArray(value)
                                                        ? value
                                                        : value?.allFileList || value?.urlList || [];
                                                    let isAllFileUploaded = true;
                                                    if (hasIn(result[0], 'status')) {
                                                        isAllFileUploaded =
                                                            result.filter(f => f.status !== 'done').length === 0;
                                                    }
                                                    if (result.length && isAllFileUploaded) {
                                                        callback();
                                                    } else {
                                                        callback('请上传证件照');
                                                    }
                                                }
                                            }
                                        ]
                                    })}
                                    accept="image/*"
                                    businessCode="SysAvatar"
                                />
                                <p className={styles.uploadInfo}>
                                    请上传您的2寸白底、近半年内的个人证件照。<br></br>
                                    照片要求：正面免冠，头发不遮挡眉毛、眼睛和脸颊，露出耳朵。
                                </p>
                                <p className={styles.formatInfo}>支持.png .jpg .jpeg格式</p>
                            </div>
                        </ListItem>
                    </List>
                </Accordion.Panel>
                <Accordion.Panel header="电脑偏好">
                    <div className={styles.subtitle}>
                        请选择您的电脑偏好，IT部门会根据您的偏好，尽量为您挑选合适的电脑：
                    </div>
                    <List className={styles.softList}>
                        <Item extra={<RadioButton dataSource={deviceTypeList} {...getFieldProps('computerType')} />}>
                            电脑类型
                        </Item>
                        <Item extra={<RadioButton dataSource={systemTypeList} {...getFieldProps('systemType')} />}>
                            系统类型
                        </Item>
                        <Item extra={<RadioButton dataSource={hasNeed} {...getFieldProps('needDisplay')} />}>
                            配备显示器
                        </Item>
                        <Item extra={<RadioButton dataSource={hasNeed} {...getFieldProps('needMouse')} />}>
                            配备鼠标
                        </Item>
                    </List>
                </Accordion.Panel>
                <Accordion.Panel header="预装软件">
                    <List className={styles.softList}>
                        <Item>
                            通用软件
                            <table className={styles.softTable}>
                                <thead>
                                    <tr>
                                        <th>
                                            软件类型
                                            <span>|</span>
                                        </th>
                                        <th>软件名称</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {softTableData.map(item => (
                                        <tr key={item.id}>
                                            <td>{item.softType}</td>
                                            <td>{item.softName}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </Item>
                        <Item extra={selectedSoft.join('、')} arrow="horizontal" onClick={handleOpenSoftPop}>
                            专业软件
                        </Item>
                        <Item extra={selectedSoft2.join('、')} arrow="horizontal" onClick={handleOpenSoftWarePop}>
                            更多软件
                        </Item>
                        <CheckboxPop
                            dataSource={softSelectData}
                            {...getFieldProps('softwareList')}
                            visible={visible}
                            onClose={handleOnClose}
                            onChange={handleOnChange}
                        />
                        <MoreSoftware
                            form={form}
                            dataSource={softWareSelectData}
                            {...getFieldProps('moreSoftwareList')}
                            visible={visible2}
                            onClose={handleOnCloseSoftWare}
                            onChange={handleOnChangeSoftWare}
                        />
                    </List>
                </Accordion.Panel>
            </Accordion>
        </Spin>
    );
});

export default createForm()(StepUserInfo);
